package com.ruoyi.framework.interceptor;

import com.ruoyi.common.annotation.RateLimiterAnnotation;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.system.service.RateLimiterService;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dingling
 * @desc 限流拦截类
 * @date 2023-07-17 14:28
 **/

@Component
public class RateLimiterInterceptor implements HandlerInterceptor {
    @Resource
    private RateLimiterService accessLimitService;

    private final Logger logger = LoggerFactory.getLogger(RateLimiterInterceptor.class);

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler){
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String uri = request.getRequestURI();

        RateLimiterAnnotation rateLimiterAnnotation = handlerMethod.getMethod().getAnnotation(RateLimiterAnnotation.class);
        if(rateLimiterAnnotation == null) {
            return true;
        }

        if (!accessLimitService.tryAcquire(uri,rateLimiterAnnotation.rateLimiterNumber())) {
            logger.info("限流中......");
            throw new BaseException("网络走丢了，请稍后重试！");
//            return false;
        }
        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {

    }
}
